package com.lemon.ai.socket.packets.spiritgame.model.xml;

import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {

	
	/**
	 * {@link XMLParser} 实例
	 */
	private static final XMLParser instance = new XMLParser();

	private Map<String, Contact> map = new HashMap<String, Contact>();
	
	/**
	 * 私有化构造
	 */
	private XMLParser() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document document;
		try {
			db = dbf.newDocumentBuilder();
			document = db.parse("keys.xml");
			
			
			init(document.getChildNodes());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void init(NodeList nodes) {
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			NodeList ns = node.getChildNodes();
			for (int j = 0; j < ns.getLength(); j++) {
				Node item = ns.item(j);
				
				NodeList ns2 = item.getChildNodes();
				
				
				Contact c = createContact(ns2);
				
				map.put(c.tableName, c);
			}
		}
	}

	private Contact createContact(NodeList ns2) {
		String tableName = ns2.item(0).getTextContent();
		String key1 = ns2.item(1).getTextContent();
		String key2 = ns2.item(2).getTextContent();
		return new Contact(tableName, key1, key2);
	}

	/**
	 * 获取该对象唯一实例
	 * @return
	 */
	public static final XMLParser getInstance() {
		return instance;
	}

	public static void main(String[] args) {
		XMLParser ins = XMLParser.getInstance();
		System.out.println(ins.contains("user_data_friends"));
		
		for (Contact c : ins.map.values()) {
			System.out.println(c);
		}
		
//		NodeList nodes = ins.getNodes();
//		System.out.println(nodes.getLength());
//		for (int i = 0; i < nodes.getLength(); i++) {
//			Node item = nodes.item(i);
//			System.out.println(item.getNodeName());
//			NodeList cNodes = item.getChildNodes();
//			for (int j = 0; j < cNodes.getLength(); j++) {
//				Node node = cNodes.item(j);
//				System.out.println(node.getNodeName());
//			}
//		}
	}
	
	public boolean contains(String tableName) {
		return map.containsKey(tableName);
	}

	public static class Contact {
		public final String tableName;
		public final String key1;
		public final String key2;
		public Contact(String tableName, String key1, String key2) {
			this.tableName = tableName;
			this.key1 = key1;
			this.key2 = key2;
		}
		
		@Override
		public String toString() {
			return "tableName = " + tableName + "	key1 = " + key1 + "	key2 = " + key2;
		}
		
	}

	public Contact getContact(String name) {
		return map.get(name);
	}
}
